package com.jeasonzhao.model.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.PersistentClass;

public class ConfiguredHBHelper extends AbstractHBHelper
{
    private static final Log log = LogFactory.getLog(ConfiguredHBHelper.class);
    private ThreadLocal threadLocal = new ThreadLocal();
    private Configuration cfg = new org.hibernate.cfg.AnnotationConfiguration();
    private org.hibernate.SessionFactory sessionFactory;
    private String configFile = null;
    public ConfiguredHBHelper(String strFileName)
    {
        log.debug("Load hibernate from " + strFileName);
        this.configFile = strFileName;
        buildFactory();
    }

    private ConfiguredHBHelper()
    {
        super();
    }

    public Session currentSession()
        throws HBException
    {
        try
        {
            Session s = (Session) threadLocal.get();
            if(s == null)
            {
                buildFactory();
                s = sessionFactory.openSession();
                threadLocal.set(s);
            }
            return s;
        }
        catch(HibernateException e)
        {
            throw new HBException(e);
        }

    }

    private void buildFactory()
        throws HibernateException
    {
        if(sessionFactory == null)
        {
            synchronized(cfg)
            {
                if(sessionFactory == null)
                {
                    cfg.configure(configFile);
                    sessionFactory = cfg.buildSessionFactory();
                    for(java.util.Iterator it = cfg.getClassMappings();null != it && it.hasNext();)
                    {
                        PersistentClass c = (PersistentClass) it.next();
//                        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>."+c.getMappedClass());
                        HBMappingFactory.getInstance().getHBMapping(c.getMappedClass());
                    }
                }
            }
        }
    }

    public void closeSession()
        throws HBException
    {
        try
        {
            Session session = (Session) threadLocal.get();
            threadLocal.set(null);
            if(session != null)
            {
                session.close();
            }
        }
        catch(HibernateException e)
        {
            throw new HBException(e);
        }
    }

    public String getConfigFile()
    {
        return configFile;
    }

    public void setConfigFile(String configFile)
    {
        this.configFile = configFile;
    }

}
